<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-tickets"></i> 学员管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" size="success" @click="handleGiveCouponShow(1)">统一发券</el-button>
            </div>
            <div class="handle-box">
                <el-input v-model.lazy="select_word" placeholder="输入微信名称关键词" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="search" @click="search();cur_page = 1">搜索</el-button>
            </div>
            <el-table :data="tableData" border ref="multipleTable" v-loading="loadingFlag">
                <!-- <el-table-column type="index" width="40"></el-table-column> -->
                <!-- sortable -->
                <el-table-column label="学号" prop="student_id"></el-table-column>
                <el-table-column label="昵称（微信名）" prop="nickName"></el-table-column>
                <el-table-column label="手机号码（券）" prop="phone"></el-table-column>
                <el-table-column label="手机号码来源（券）" prop="phoneType">
                    <template slot-scope="scope">
                        {{(scope.row.phoneType === 1 ? '小程序':scope.row.phoneType === 2  ? 'APP' :'')}}
                    </template>
                </el-table-column>
                <el-table-column label="优惠券" prop="couponType">
                    <template slot-scope="scope">
                        {{(scope.row.couponType === 1 ? '小程序':scope.row.couponType === 2  ? 'APP' :'')}}
                    </template>
                    
                </el-table-column>
                <el-table-column label="APP手机号码" prop="loginPhone"></el-table-column>
                <el-table-column label="课程完成度(只记录小程序)" prop="plan">
                    <!-- <template slot-scope="scope">
                        课程完成度
                    </template> -->
                </el-table-column>
                <el-table-column label="课程完成时间（APP总通关）" prop="total_tas"></el-table-column>
                <el-table-column label="交作业次数" prop="submit_total"></el-table-column>
                <el-table-column label="累计打卡" prop="sign_in_total"></el-table-column>
                <el-table-column label="付费金额">
                    <template slot-scope="scope">
                        {{(scope.row.amount / 100).toFixed(2)}}
                    </template>
                </el-table-column>
                <el-table-column label="是否后台添加的人员">
                    <template slot-scope="scope">
                        {{scope.row.type === '4'? '是': ''}}
                    </template>
                </el-table-column>
                <el-table-column label="已获奖励">
                    <template slot-scope="scope">
                        
                        <div>{{ scope.row.coupon_id ? '金奖劵，': ''}}</div>
                        <div>{{ scope.row.g_id ?  '礼盒，': ''}}</div>
                    </template>
                </el-table-column>
                
                <el-table-column label="操作" width="600">
                    <template slot-scope="scope">
                        <el-button size="small" @click="courseSectionShow(scope.row)">补打卡(可查看通关)</el-button>
                        <el-button size="small" type="info" @click="openJobListVisible(scope.row)">个人作业</el-button>
                        <el-button size="small" type="success" @click="giveStudentCoupon(scope.row)">发放卡卷</el-button>
                        <el-button size="small" type="warning" plain @click="setStudentShutupShow(scope.row)">{{scope.row.shutup ? '解除禁言' : '禁言'}}</el-button>
                        <el-button size="small" type="danger" @click="studentExpelShow(scope.row)">开除</el-button>
                        <el-button size="small" :type="scope.row.super_user == 1 ? 'warning' :  'primary'" @click="studentSetSuperShow(scope.row)">{{scope.row.super_user == 1 ? '取消超级用户': '设置超级用户'}}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination @current-change="handleCurrentChange" layout="prev, pager, next, jumper" :total="total" :page-size="10">
                </el-pagination>
            </div>
        </div>
        <!-- 打卡列表 -->
        <el-dialog width="80%"  :visible.sync="studentClockShow" v-loading="studentClockListLoading">
            <el-table :data="studentClockList" border>
                <el-table-column label="课程名" prop="section_name"></el-table-column>
                <el-table-column label="第几天" prop="section_day"></el-table-column>
                <el-table-column label="课程进程" prop="status">
                     <template slot-scope="scope">
                        {{scope.row.status == 1 ? '进行中': scope.row.status == 2 ? '已结束' : '未开始'}}
                    </template>
                </el-table-column>
                <el-table-column label="通关（app）" prop="today_tas">
                     <template slot-scope="scope">
                        {{scope.row.today_tas == 1 ? '当日通关': scope.row.today_tas == 2 ? '非当日通关' : '未通关'}}
                    </template>
                </el-table-column>
                <el-table-column label="星评（app）" prop="all_start">
                </el-table-column>
                <el-table-column label="评分（app）" prop="all_score">
                </el-table-column>
                <el-table-column label="课程完成时间（小程序）" prop="finish_time"></el-table-column>
                <el-table-column label="打卡情况">
                    <template slot-scope="scope">
                        {{scope.row.clock_state == 1 ? '已打卡': '未打卡'}}
                    </template>
                </el-table-column>
                <el-table-column label="补打卡">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" v-if="scope.row.clock_state == 0" @click="repairClock(1,scope.row)">补打卡</el-button>
                        <el-button size="mini" type="warning" v-if="scope.row.clock_state == 1" @click="repairClock(0,scope.row)">取消打卡</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align:right;margin-top: 20px;">
                <span slot="footer" class="dialog-footer">
                    <el-button @click="studentClockShow = false">取 消</el-button>
                    <!-- <el-button type="primary" @click="setStudentShutupSubmit()">确 定</el-button> -->
                </span>
            </div>
           
        </el-dialog>
        <!-- 设置学员禁言状态 提示框 -->
        <el-dialog title="提示" :visible.sync="shutupVisible" width="300px" center>
            <div class="del-dialog-cnt">设置该学员禁言状态？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="shutupVisible = false">取 消</el-button>
                <el-button type="primary" @click="setStudentShutupSubmit()">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 学员开除 提示框 -->
        <el-dialog title="提示" :visible.sync="shutupExpelVisible" width="300px" center>
            <div class="del-dialog-cnt">设置该学员开除状态？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="shutupExpelVisible = false">取 消</el-button>
                <el-button type="primary" @click="studentExpelSubmit()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 设置超级用户 提示框 -->
        <el-dialog title="提示" :visible.sync="superVisible" width="300px" center>
            <div class="del-dialog-cnt">是否{{studentData.super_user == 1 ? '取消超级用户': '设置超级用户'}}?</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="superVisible = false">取 消</el-button>
                <el-button type="primary" @click="studentSetSuperSubmit()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 个人作业 列表 -->
        <el-dialog width="70%" title="个人作业" :visible.sync="jobListVisible">
            <!-- <el-dialog
            width="30%"
            title="内层 Dialog"
            :visible.sync="innerVisible"
            append-to-body>
            </el-dialog>-->
            <el-dialog title="作业详情" :visible.sync="dialogFormVisible" append-to-body>
                <div class="job-details">
                    <div class="table">
                        <div class="crumbs">
                            <el-breadcrumb separator="/">
                                <el-breadcrumb-item>
                                    <i class="el-icon-tickets"></i> 作业详情</el-breadcrumb-item>
                            </el-breadcrumb>
                        </div>
                        <div class="container" v-if="saveData">
                            <el-row :gutter="20">
                                <el-col :span="6">
                                    <div class="meun-title">日期时间</div>
                                    <div class="meun-item">{{saveData.create_time | formatTime}}</div>
                                </el-col>
                                <el-col :span="6">
                                    <div class="meun-title">学号</div>
                                    <div class="meun-item">{{saveData.student_id}}</div>
                                </el-col>
                                <el-col :span="8">
                                    <div class="meun-title">微信名</div>
                                    <div class="meun-item">{{saveData.nickName}}</div>
                                </el-col>
                            </el-row>
                            <div v-for="(job,jIndex) in saveData.content" :key="jIndex">
                                <!--学生作业视频-->
                                <el-card class="box-card distance-100" v-if="job.status === 1">
                                    <div v-for="(affix,aIndex) in job.content" :key="aIndex">
                                        <h3 v-if="affix.status === 10 && affix.url">作业视频附件</h3>
                                        <!-- <div id="dplayer" style="max-width: 80%;margin: 0 auto" v-if="affix.status === 10">{{videoPlayer(affix.url,affix.content)}}</div> -->
                                        <video :src="affix.url" controls width="100%" height="100%"  v-if="affix.status === 10"></video>
                                    </div>
                                </el-card>
                                <el-card class="box-card distance-100" v-if="job.status === 1">
                                    <div v-for="(affix,aIndex) in job.content" :key="aIndex">
                                        <h3 v-if="affix.status === 10 && aIndex === 0">作业图片</h3>
                                        <img :src="affix.content" v-if="affix.status === 11" style="width: 80%;margin: 10px auto;display: block">
                                    </div>
                                </el-card>
                                <el-card class="box-card distance-100" v-if="job.status === 2">
                                    <h3>作业音频附件</h3>
                                    <aplayer :music="{
                                        src: job.content,
                                        pic: 'https://moeplayer.b0.upaiyun.com/aplayer/secretbase.jpg'
                                    }" />
                                </el-card>

                                <!--学生作业文字-->
                                <el-card class="box-card distance-100" v-if="job.status === 0">
                                    <h3>作业内容</h3>
                                    {{job.content}}
                                </el-card>
                            </div>

                        </div>
                        
                        <div class="container" style="margin-top: 15px;">
                            <h3>老师点评</h3>
                            <el-input type="textarea" :disabled="disabledWrite" :autosize="{ minRows: 4, maxRows: 6}" placeholder="请输入内容" v-model="saveData.teach">
                            </el-input>
                            <div style="text-align: center;margin-top: 15px;">
                                <el-button type="primary" @click="selectTeachShow()">点评发布</el-button>
                            </div>
                        </div>
                        <div class="container" style="margin-top: 15px;">
                            <el-alert v-if="saveData.super_user === 1" title="此作业为管理员的作业，选为精选作业请注意" type="error"></el-alert>
                            <div style="text-align: center;margin-top: 15px;">
                                <el-button type="success" plain v-if="saveData.recommend" @click="setRecommend();dialogFormVisible = false;">取消精选作业</el-button>
                                <el-button type="success" plain v-if="!saveData.recommend" @click="setRecommend();dialogFormVisible = false;">选为精选作业</el-button>
                            </div>
                        </div>

                    </div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="dialogFormVisible = false">返回</el-button>
                </div>
            </el-dialog>
            <el-table :data="jobList" border ref="multipleTable" v-loading="loadingFlag">
                <!-- <el-table-column type="index" width="40"></el-table-column> -->
                <!-- sortable -->
                <el-table-column label="第几天" prop="section_number"></el-table-column>
                <el-table-column label="课程名称" prop="section_name"></el-table-column>
                <el-table-column label="课程名称" prop="section_name"></el-table-column>
                <el-table-column label="提交时间" prop="create_time">
                     <template slot-scope="scope">
                        {{scope.row.create_time - 0 | formatTime}}
                    </template>
                </el-table-column>
                <el-table-column label="点评内容" prop="teach"></el-table-column>                
                <el-table-column label="点评时间" prop="teach_time">
                     <template slot-scope="scope">
                        {{scope.row.teach_time - 0 | formatTime}}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="jobDetailsShow(scope.row)">查看详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="jobListVisible = false">取 消</el-button>
                <!-- @click="innerVisible = true" -->
                <!-- <el-button type="primary" >打开内层 Dialog</el-button> -->
            </div> 
        </el-dialog>
        <el-dialog
            title="选择教师点评"
            :visible.sync="teachVisible"
            width="300px">
            <div>
                <el-select v-model="teachValue" placeholder="请选择">
                    <el-option
                        v-for="item in teachList"
                        :key="item.student_id"
                        :label="item.nickName"
                        :value="item.student_id">
                    </el-option>
                </el-select>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="teachVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitJobComment()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 发送卡卷 -->
        <GiveCoupon :studentData="saveData" :giveCouponShow="giveCouponShow" @handleGiveCouponShow="handleGiveCouponShow($event)"/>
    </div>
</template>

<script>
import { 
    obtainStudentDetailsList,
    setStudentShutup,
    studentExpel,
    studentSetSuper,
    obtainCourseSectionList,
    studenRepairClock,
    studentSearch ,
    obtainAllJob,
    obtainTeachList,
    updateJobComment ,
    cancelJobRecommend ,
    setJobRecommend} from "@/config/api";
import {dateRegExp} from '@/config/filter';
import GiveCoupon from '@/components/page/GiveCoupon/GiveCoupon.vue'
export default {
    components: {
        GiveCoupon,
    },
    name: "basetable",
    data() {
        return {
            url: "./static/vuetable.json",
            tableData: [],
            cur_page: 1,
            select_cate: "",
            select_word: "",
            del_list: [],
            is_search: false,
            
            // 设置学员禁言 提示框 显示
            shutupVisible: false,
            // 学员开除 提示框 显示
            shutupExpelVisible : false,
            // 设置超级用户 提示框 显示
            superVisible: false,
            // 个人作业列表 提示框 显示
            jobListVisible: false,
            // 批次ID
            batch_id: "",
            // 总条数
            total: 0,
            // 学员数据
            studentData: {},
            // 加载
            loadingFlag: false,
            // 补打卡的列表
            studentClockShow: false,
            // 学员的打卡
            studentClockList: [],
            // 打卡数据加载 loading
            studentClockListLoading: false,
            // 作业列表
            jobList: [],

            // 作业详情 显示
            dialogFormVisible: false,
            textarea: "",
            // 删除作业 对话框 显示
            delVisible: false,
            // 是否设置为精选作业 对话框 显示
            recommendVisible: false,
             // 保存被点击的数据
            saveData: {},
            // 选择教师点评
            teachVisible: false,
            // 教师列表
            teachList: [],
            // 选择了那个教师
            teachValue: '',
            // 视频播放中，禁止输入
            disabledWrite: false,
            // 发送卡卷弹窗 显示 0隐藏 1给该批次添加卡卷 2给该学员添加卡卷 3添加成功隐藏卡卷弹窗并刷新列表
            giveCouponShow: 0,
        };
    },
    filters: {
        formatTime (time) {
            return time ? dateRegExp(( time - 0 ),'yyyy-MM-dd hh:mm:ss') : ''
        }
    },
     watch: {
      // 深度监听
      $route: {
          handler(item){
              let self = this;
              if(JSON.stringify(item.query) != '[]') {
                this.getData();
              }
          },
          deep:true
      },
    },
    created() {
        this.getData();
    },
    computed: {},
    methods: {
        // 获取 列表
        async getData() {
            this.loadingFlag = true;
            await obtainStudentDetailsList(this.cur_page,this.$route.query.batch_id)
                .then(res => {
                    console.log('列表：',res)
                    this.tableData = res.list
                    this.total = res.total
                    this.loadingFlag = false;
                })
                .catch(err => {
                    console.error('失败:',err)
                    this.loadingFlag = false;
                });
        },
        // 设置学员禁言  显示
        setStudentShutupShow (row) {
            this.shutupVisible = true;
            this.studentData = row;
        },
        // 设置学员禁言  提交
        async setStudentShutupSubmit () {
            // 设置学员禁言  隐藏
            this.shutupVisible = false;
            // 提交
            await setStudentShutup(this.studentData.student_id)
                .then(res => {
                    console.log('设置禁言：',res)
                    if (res.msg === 'success') {
                        this.getData()
                        this.$message({
                            type: "success",
                            message: "设置成功!"
                        });
                    } else {
                        this.$message.error("设置失败" + str);
                    }
                })
                .catch(err => {
                    console.error('失败:',err)
                });
        },
         // 学员开除 提示框 显示
        studentExpelShow (row) {
            this.shutupExpelVisible = true;
            this.studentData = row;
        },
        // 学员开除 提交
        async studentExpelSubmit () {
            // 设置学员禁言  隐藏
            this.shutupExpelVisible = false;
            // 提交
            await studentExpel(this.studentData.student_id)
                .then(res => {
                    console.log('开除',res)
                    if (res.msg === 'success') {
                        this.getData()
                        this.$message({
                            type: "success",
                            message: "开除成功!"
                        });
                    } else {
                        this.$message.error("开除失败" + str);
                    }
                })
                .catch(err => {
                    console.error('失败:',err)
                });
        },
        // 设置超级用户 提示框 显示
        studentSetSuperShow (row) {
            this.superVisible =  true;
            this.studentData = row;
        },
        // 设置超级用户 提交
        async studentSetSuperSubmit () {
            // 设置学员禁言  隐藏
            this.superVisible = false;
            console.log(this.studentData)
            let num = this.studentData.super_user
            // 提交  0取消超级用户 1设置超级用户
            await studentSetSuper(this.studentData.student_id,num == 1 ? 0 : 1)
                .then(res => {
                    console.log('开除设置超级用户',res)
                    if (res.msg === 'success') {
                        if (this.is_search) {
                            this.search();
                        } else {
                            this.getData();
                        }
                        this.$message({
                            type: "success",
                            message: "设置成功!"
                        });
                    } else {
                        this.$message.error("设置失败" + str);
                    }
                })
                .catch(err => {
                    console.error('失败:',err)
                });
        },
        //  参与的课程列表 显示
        async courseSectionShow (row) {
            console.log(row,'................')
            this.studentClockShow =  true;
            this.studentData = row;
            this.courseSectionReq()
        },
        // 获取学员参与的课程列表
        async courseSectionReq () {
            this.studentClockListLoading = true
            await obtainCourseSectionList(this.studentData.student_id)
                .then( res => {
                    console.log(res,'学员的课程列表')
                    if (res.status === 200) {
                        this.studentClockList = res.data;
                    }
                    this.studentClockListLoading = false;
                })
                .catch(err => {
                    this.studentClockListLoading = false;
                })
        },
        // 学员补打卡 type 1 补打 0取消打卡
        async repairClock (type,item) {
            await studenRepairClock(this.studentData.student_id,this.$route.query.batch_id ,item.section_id,type)
                .then( res => {
                    if (res.status === 200) {
                        this.studentClockList = res.data;
                        this.courseSectionReq() // 重新获取打卡数据
                    } else {
                        this.$message.error("网络拥堵");
                    }
                })
        },
        // 分页导航
        handleCurrentChange(val) {
            this.cur_page = val;
           
            if (this.is_search) {
                this.search();
            } else {
                this.getData();
            }
        },
        // 学员搜索
        async search() {
            if (!this.select_word) {
                this.cur_page = 1
                this.getData();
                this.is_search = false;
                return false;
            }
            this.is_search = true;
            this.loadingFlag = true;
            await studentSearch(this.$route.query.batch_id,this.select_word.replace(/^\s+|\s+$/g,''),this.cur_page)
                .then( res => { 
                    console.log('学员搜索',res)
                    if (res.status === 200) {
                        this.tableData = res.data
                        this.total = res.total
                    } else {
                        this.$message.error("搜索失败");
                    }
                    this.loadingFlag = false;
                })
                .catch( err => {
                    this.loadingFlag = false;
                })
        },
        // 打开个人作业列表
        async openJobListVisible (row) {
            this.jobListVisible = true;
            let data = await obtainAllJob(row['student_id']);
            this.jobList = data.data || [];
            console.log(row,data,'打开个人作业列表');
        },
        // 作业详情显示
        jobDetailsShow(row) {
            console.log("作业详情显示:", row);
            this.saveData = row;
            this.dialogFormVisible = true;
            this.saveData.content.comment =
                row.content && row.content.comment ? row.content.comment : "";
            // setTimeout(() => {
            //     this.videoPlayer(row.content.video)
            // }, 300);
        },
        // 获取此批次下的教师
        async selectTeachShow () {
            try {
                this.teachValue = '';
                let teach =  await obtainTeachList(this.$route.query.batch_id)
                this.teachVisible = true;
                this.teachList = teach.data;
            } catch (e) {
                console.error(e)
            }
        },
        // 提交老师点评
        async submitJobComment() {
            if (!this.saveData.teach) {
                this.$message.error('请输入点评内容');
                return false;
            };
            if (!this.teachValue) {
                this.$message.error('请选择教师');
                return false;
            }
            this.dialogFormVisible = false;
            this.teachVisible = false;
            await updateJobComment(this.saveData.job_id, this.saveData.teach,this.teachValue)
                .then(res => {
                    console.log("提交老师点评:", res);
                    if (res.msg === "success") {
                        // 重新获取数据
                        this.obtainStudent();
                        this.$message({
                            type: "success",
                            message: "点评成功!"
                        });
                    } else {
                        this.$message.error("失败");
                    }
                    this.getData();
                    // 重新获取详作业列表
                    this.openJobListVisible(this.saveData);
                })
                .catch(err => {
                    console.error("失败:", err);
                    this.getData();
                });
        },
        // 设置为精选评论 显示
        setRecommendShow(index, row) {
            this.recommendVisible = true;
            this.saveData = row;
        },
        // 设置为精选评论
        async setRecommend() {
            this.recommendVisible = false;
            if (this.saveData.recommend) {
                await cancelJobRecommend(this.saveData.job_id)
                    .then(res => {
                        console.log("取消为精选评论:", res);
                        if (res.msg === "success") {
                            this.$set(this.saveData, "recommend", 1);
                            this.$message({
                                type: "success",
                                message: "取消成功!"
                            });
                        } else {
                            this.$message.error("失败" + str);
                        }
                        // 重新获取数据
                        this.getData();
                        // 重新获取详作业列表
                        this.openJobListVisible(this.saveData);
                    })
                    .catch(err => {
                        console.error(err);
                    });
            } else {
                await setJobRecommend(this.saveData.job_id)
                    .then(res => {
                        console.log("设置为精选评论:", res);
                        if (res.msg === "success") {
                            this.$set(this.saveData, "recommend", 0);
                            this.$message({
                                type: "success",
                                message: "设置成功!"
                            });
                        } else {
                            this.$message.error("失败" + str);
                        }
                        // 重新获取数据
                        this.getData();
                        // 重新获取详作业列表
                        this.openJobListVisible(this.saveData);
                    })
                    .catch(err => {
                        console.error(err);
                    });
            }
        },
        // 发送卡卷弹窗 显示
        handleGiveCouponShow (status) {
             // 发送卡卷弹窗 显示 0隐藏 1给该批次添加卡卷 2给该学员添加卡卷 3添加成功隐藏卡卷弹窗并刷新列表
            this.giveCouponShow = status;
            if (status === 3) {
                // 重新获取数据
                this.getData();
            }
        },
        // 给单个学员发放卡卷
        giveStudentCoupon (row) {
            this.giveCouponShow = 2;
            this.saveData = row;
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.del-dialog-cnt {
    font-size: 16px;
    text-align: center;
}
</style>
